import requests
from datetime import datetime
from typing import Literal

class TrafficService:


    # 通过高德地图API获取分段指标数据
    # 1 拥堵延时指数   2 高延时运行时间占比(%)   3 拥堵路段里程比(%)   
    # 4 平均车速(km/h)   5 道路运行速度偏差率(%)  
    @staticmethod
    def get_time_distribution(data_type):
        """获取时段分析数据"""
        url = 'https://report.amap.com/ajax/cityHourly.do'
        params = {
            'cityCode': '420100',  # 武汉市城市编码
            'dataType': data_type  # 数据类型
        }
        
        response = requests.get(url, params=params)
        data = response.json()
        
        # 处理数据格式
        formatted_data = []
        for timestamp, value in data:
            time = datetime.fromtimestamp(timestamp / 1000)  # 转换毫秒时间戳
            hour = time.strftime('%H时')
            formatted_data.append({
                'time': hour,
                'value': round(value, 2)  # 保留两位小数
            })
            
        return formatted_data

    @staticmethod
    def get_congestion_data(bounds_list):
        """获取拥堵数据"""
        from .baidu_map_service import BaiduMapService
        
        # 存储所有响应
        all_responses = []
        
        # 请求每个区域的数据
        for bounds in bounds_list:
            data = BaiduMapService.get_bound_traffic(bounds)
            if data['status'] == 0:
                all_responses.append(data)
        
        return all_responses 

    @staticmethod
    def get_district_rank(links_type: Literal["1", "3", "4"]) -> dict:
        """获取高德地图区域排名数据
        
        Args:
            links_type: 排名类型
                1: 区域拥堵排名
                3: 商圈排名
                4: 行政区划排名
        """
        try:
            url = "https://report.amap.com/ajax/districtRank.do"
            params = {
                "linksType": links_type,
                "cityCode": "420100"  # 武汉市城市编码
            }
            
            response = requests.get(url, params=params, timeout=10)
            response.raise_for_status()
            
            data = response.json()
            if not data:
                raise ValueError("未获取到排名数据")
            
            # 处理数据
            rank_list = []
            for item in data:
                try:
                    rank_list.append({
                        "name": item["name"],
                        "value": round(float(item["index"]), 2),
                        "speed": round(float(item["speed"]), 2),
                    })
                except (KeyError, ValueError, TypeError) as e:
                    print(f"数据格式错误: {str(e)}")
                    continue
            
            if not rank_list:
                raise ValueError("数据处理后为空")
            
            # 按拥堵指数从高到低排序
            rank_list.sort(key=lambda x: x["value"], reverse=True)
            
            return {
                "success": True,
                "data": rank_list
            }
            
        except requests.Timeout:
            print("请求超时")
            return {
                "success": False,
                "message": "请求超时，请稍后重试"
            }
        except requests.RequestException as e:
            print(f"请求错误: {str(e)}")
            return {
                "success": False,
                "message": "网络请求失败"
            }
        except Exception as e:
            print(f"获取区域排名数据失败: {str(e)}")
            return {
                "success": False,
                "message": "获取区域排名数据失败"
            } 

    @staticmethod
    def get_traffic_indicators() -> dict:
        """获取高德地图9项交通指标数据"""
        try:
            url = "https://report.amap.com/diagnosis/ajax/9indicators.do"
            params = {
                "type": "24",  # 24小时
                "adcode": "420100"  # 武汉市行政区划代码
            }
            
            response = requests.get(url, params=params, timeout=10)
            response.raise_for_status()
            
            data = response.json()
            
            return {
                "success": True,
                "data": data
            }
            
        except requests.Timeout:
            print("请求超时")
            return {
                "success": False,
                "message": "请求超时，请稍后重试"
            }
        except requests.RequestException as e:
            print(f"请求错误: {str(e)}")
            return {
                "success": False,
                "message": "网络请求失败"
            }
        except Exception as e:
            print(f"获取指标数据失败: {str(e)}")
            return {
                "success": False,
                "message": "获取指标数据失败"
            } 